package client.command;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import util.Command;
import util.Constant;
import util.Control;

public class Get extends Command{
	
	private OutputStream out;
	private InputStream in;
	private String file;
	
	public Get(Socket socket,String file) throws IOException{
		setSocket(socket);
		out = getSocket().getOutputStream();
		in = getSocket().getInputStream();
		this.file = file;
	}
	
	private void sendControlMessenger (Control msg) throws IOException{
		DataOutputStream data_out = new DataOutputStream(out);
		data_out.flush();
		data_out.writeInt(msg.Code());
	}
	
	/*
	 * protocolo para Get:
	 * Envia:  GET
	 * Recebe: RECEIVED
	 * --
	 * Envia:  NOME DO ARQUIVO
	 * Recebe: TAMANHO DO ARQUIVO
	 * Recebe: ARQUIVO
	 * --
	 */
	public void get(String file){		
		try {
			DataInputStream data_in = new DataInputStream(in);
			
			sendControlMessenger(Control.GET);
			
			if(data_in.readInt()!=Control.RECEIVED.Code()) throw new Exception("ERROR SINCRONIZACAO");
			
			receiveFile(file);
			
		} catch (IOException e) {			
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void receiveFile(String fileName) throws IOException {	
		DataInputStream data_in = new DataInputStream(in);
		DataOutputStream data_out = new DataOutputStream(out);
		
		data_out.writeUTF(fileName); 
		
		long size_file = data_in.readLong();
		
		System.out.println("Recebendo arquivo: " + fileName + " Tamanho: " + size_file);
		
		File file = new File("client/" + fileName);
		FileOutputStream out_file = new FileOutputStream(file);
		
		byte[] buffer = new byte[Constant.SIZE_BUFFER_CLIENT];
		int bytes_read = -1;
		long total_read = 0;

		while (total_read < size_file){
			bytes_read = in.read(buffer, 0, Constant.SIZE_BUFFER_CLIENT);
			out_file.write(buffer, 0, bytes_read);
			total_read+=bytes_read;
		}
		
		out_file.close();
		System.out.println("Arquivo: " + fileName + " Recebido.");
	}
	
	public void execute() {	
		get(file);
	}

}
